//
//  CloudApiService+Serve.swift
//  Health-Doctor
//
//  Created by woniu on 2025/8/1.
//  Copyright © 2025 掌上卫健. All rights reserved.
//

import Foundation
import HandyJSON

struct ScreeningCompare:HandyJSON{
    //随访日期
    public var sfrq = ""
    //舒张压
    public var szy = ""
    //收缩压
    public var ssy = ""
    //空腹血糖值
    public var kfxtz = ""
    //随机血糖值
    public var sjxt = ""
    
    public var personCodeOrIdCard = ""
    
    //相同数据
    public func isEquel(by model:ScreeningCompare)->Bool{
        if self.sfrq == model.sfrq && self.szy == model.szy && self.ssy == model.ssy && self.kfxtz == model.kfxtz && self.sjxt == model.sjxt{
            return true
        }
        return false
    }
    
    public static func createBy(woniuData:[String:Any])->ScreeningCompare{
        let screeningData = woniuData.dictionary("screeningData")
        var model = ScreeningCompare()
        //筛查日期
        model.sfrq = woniuData.dictionary("screeningRecord").strValue("screeningDate").subString(to: 10)
        //收缩压
        model.ssy = screeningData.strValue("spb")
        //舒张压
        model.szy = screeningData.strValue("dpb")
        //空腹血糖
        model.kfxtz = screeningData.strValue("bloodSugar")
        //随机血糖
        model.sjxt = screeningData.strValue("randomBloodGlucose")
        
        return model
    }
    
    public func toStr()->String{
        let json = self.toJSONString() ?? ""
        return json
    }
}

extension CloudApiService{
    
    
    /// 根据指定参数，查找健康筛查
    /// - Parameters:
    ///   - param: 参数
    ///   - finish: 回调
    public func httpFindScreeningBy(param:ScreeningCompare,finish:@escaping((_ re:Bool,_ item:[String:Any])->())){
        let findBlock = {[weak self]in
            guard let `self` = self else { return }
            self.apiFindScreeningItemBy(param: param, token: self.token, sid: self.sid, uuid: self.uuid, areaId: self.areaId, finish: finish)
        }
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "根据指定参数查找健康筛查，发现未登录，去登录")
            self.onLoginSuccessBlock = findBlock
            self.reAutoLogin()
        }else{
            findBlock()
        }
    }
    
    /// 新建健康筛查
    /// - Parameters:
    ///   - data: 数据
    ///   - finish: 回调
    public func httpCreateScreening(woniuData:[String:Any],cloudRhrId:String,finish:@escaping((_ re:Bool,_ dataId:String)->())){
        let createBlock = {
            //转码
            self.httpChangeWoniuScreeningToCloudStyle(woniuData: woniuData) {[weak self] re, cloudData in
                guard let `self` = self else { return }
                if re{
                    //保存
                    var params = cloudData
                    params["daId"] = cloudRhrId
                    self.apiCreateScreening(data: params,token: self.token, sid: self.sid, uuid: self.uuid,finish: finish)
                }
            }
            
        }
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "准备保存健康筛查，发现未登录，去登录")
            self.onLoginSuccessBlock = createBlock
            self.reAutoLogin()
        }else{
            createBlock()
        }
    }
    
    /// 更新健康筛查
    /// - Parameters:
    ///   - data: 数据
    ///   - finish: 回调
    public func httpUpdateScreening(woniuData:[String:Any],cloudRhrId:String,jkscSfId:String,finish:@escaping((_ re:Bool)->())){
        let updateBlock = {
            self.httpChangeWoniuScreeningToCloudStyle(woniuData: woniuData) {[weak self] re, cloudData in
                guard let `self` = self else { return }
                if re{
                    var params = cloudData
                    //档案ID
                    params["daId"] = cloudRhrId
                    //对应云平台 健康筛查随访ID
                    params["jkscSfId"] = jkscSfId
                    self.aipUpdateScreening(cloudData: params, token: self.token, sid: self.sid, uuid: self.uuid, finish: finish)
                }
            }
        }
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "更新健康筛查，发现未登录，去登录")
            self.onLoginSuccessBlock = updateBlock
            self.reAutoLogin()
        }else{
            updateBlock()
        }
    }
    
    
    /// 两只蜗牛格式的健康筛查 => 云平台格式
    /// - Parameters:
    ///   - woniuData: 蜗牛格式数据
    ///   - finish: 回调
    private func httpChangeWoniuScreeningToCloudStyle(woniuData:[String:Any],finish:@escaping((_ re:Bool,_ cloudData:[String:Any])->())){
        let action = ServiceAction.woniuScreeningStyleToCloudStyle(param: woniuData)
        MyMessage.showWaitHUD()
        serviceProvider.httpRequst(action) { result in
            MyMessage.hiddenWaitHUD()
            if result.isSuccess(){
                let dic = result.dicData()
                finish(true,dic)
                
            }else{
                MyMessage.showText(message: result.msg)
                finish(false,[:])
            }
        }
    }
  
}


//健康筛查
extension CloudApiService{
    
    //健康筛查创建
    private func apiCreateScreening(data:[String:Any],token:String,sid:String,uuid:String,finish:@escaping((_ re:Bool,_ dataId:String)->())){
        let ipAddress = getIpAddress()
        let url = URL(string: "\(ipAddress)/ehrc/ehr/jksc/create")!
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        // 设置请求头
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(ipAddress, forHTTPHeaderField: "Origin")
        request.setValue("Op39geboOf74Tf8XA/ZHwoZMN614drlgUhuLXjjLLtZiCCzLsePLLMt4qmeGRGe0Orco/WosHUknIJJLTJGyCHpF0qDiGa84f937mBG8T8SUwuCcX68R6J0YagvbXGt1NJ0fHF9ZgjKBZqwQG6dGfiBwf06TVMKrVc3gM8EUTmW8sB1HmnEJI7aOzASMl6cA6Dsf2JiWJKb7GOK3rNQxJZl5zzV3QCEpVz4mkEBHMkA=", forHTTPHeaderField: "Jom-Rjkmj-Jrjm")
        request.setValue("dOLoMguEGjfYtl9L", forHTTPHeaderField: "Oew-Nrcow-Awqq")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("\(ipAddress)/index.html", forHTTPHeaderField: "Referer")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        let cookie = "sid=\(sid); token=\(token); uuid=\(uuid)"
        request.setValue(cookie, forHTTPHeaderField: "Cookie")
        
        if let jsonData = try? JSONSerialization.data(withJSONObject: data){
            request.httpBody = jsonData
        }
        request.writeToLogFile()
        
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "保存健康筛查接口返回->\(responseString)")
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataDic = dic.dictionary("data")
                        let dataId = dataDic.strValue("data")
                        finish(true,dataId)
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false,"")
                    }
                }else{
                    MyMessage.showText(message: "查询失败，请重试")
                    finish(false,"")
                }
            }
            
        }
        task.resume()
    }
    
//    //健康筛查详情
//    private func apiGetScreeningDetail(dataId:String,token:String,sid:String,uuid:String,finish:@escaping((_ re:Bool,_ detail:[String:Any])->())){
//        let ipAddress = getIpAddress()
//        let urlString = "\(ipAddress)/ehrc/ehr/jksc/\(dataId)"
//        guard let url = URL(string: urlString) else {
//            print("Invalid URL")
//            return
//        }
//        
//        // 创建 URLRequest
//        var request = URLRequest(url: url)
//        request.httpMethod = "GET"
//        
//        // 设置请求头
//        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
//        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
//        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
//        request.setValue("\(ipAddress)/index.html", forHTTPHeaderField: "Referer")
//        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
//        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
//        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
//        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
//        let cookieHeader = "sid=\(sid); uuid=\(uuid)"
//        request.setValue(cookieHeader, forHTTPHeaderField: "Cookie")
//        
//        request.writeToLogFile()
//        
//        MyMessage.showWaitHUD()
//        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
//            MyMessage.hiddenWaitHUD()
//            guard let `self` = self else { return }
//            DispatchQueue.main.async {
//                
//                if let data = data, let responseString = String(data: data, encoding: .utf8) {
//                    self.printWrite(log: "获取健康筛查详情接口返回->\(responseString)")
//                    let dic = responseString.toDic()
//                    let httpCode = dic.intValue("code")
//                    
//                    if httpCode == 200{
//                        let dataDic = dic.dictionary("data")
//                        let detail = dataDic.dictionary("data")
//                        finish(true,detail)
//                        
//                    }else{
//                        let httpErrorMsg = dic.strValue("message")
//                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
//                        finish(false,[:])
//                    }
//                }else{
//                    MyMessage.showText(message: "查询失败，请重试")
//                    finish(false,[:])
//                }
//            }
//            
//        }
//        
//        // 启动任务
//        task.resume()
//    }
//    
    
    
    /// 更新健康筛查
    /// - Parameters:
    ///   - data: 数据
    ///   - token:
    ///   - sid:
    ///   - uuid:
    ///   - finish:
    public func aipUpdateScreening(cloudData:[String:Any],token:String,sid:String,uuid:String,finish:@escaping((_ re:Bool)->())){
        
        let ipAddress = getIpAddress()
        let urlString = "\(ipAddress)/ehrc/ehr/jksc/update"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        
        // 2. 准备URLRequest
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = "PUT"
        
        // 3. 设置Headers
        let headers: [String: String] = [
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh-Hans;q=0.9",
            "accessToken": token,
            "Connection": "keep-alive",
            "Content-Type": "application/json",
            "Origin": ipAddress,
            "Priority": "u=3, i",
            "Referer": "\(ipAddress)/mb.html",
            "User-Agent": getUserAgent(),
            "Ehx-Ogyxg-Soex": "AlF+G6O9XnodWjtZRDfivCHvSoIcLZGwlE9R2YwNJa6J+K48st4Bvu+4g4oBWOA4jE1f9uT5koRDkR2ZAKauIqZd58XzoDBqqILf0ZhpXnn2fgZLb6TrqgCWoYVzp7Cp8Z2VXyWYRLpXEeTb8+Aers2vK2gk6wzaQNBdzKJ7boQQI16WlhmIzrD1PfWpENlTGVistXdcbX91bMkEek1gqJzlMMFyBY6UF7cNMdu/CiE=",
            "Med-Oolpa-Boap": "75BKnqGhSwvKyPK9"
        ]
        
        headers.forEach { key, value in
            urlRequest.setValue(value, forHTTPHeaderField: key)
        }
        let cookie = "token=\(token); sid=\(sid); uuid=\(uuid)"
        urlRequest.setValue(cookie, forHTTPHeaderField: "Cookie")
        if let jsonData = try? JSONSerialization.data(withJSONObject: cloudData){
            urlRequest.httpBody = jsonData
        }
        
        urlRequest.writeToLogFile()
        
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: urlRequest) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "更新筛查接口返回->\(responseString)")
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        finish(true)
                        
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false)
                    }
                }else{
                    MyMessage.showText(message: "操作失败，请重试")
                    finish(false)
                }
            }
            
        }
        
        // 启动任务
        task.resume()
    }
    
    
    /// 根据给定参数，去云平台找该条数据
    /// - Parameters:
    ///   - param: 参数
    ///   - token:
    ///   - sid:
    ///   - uuid:
    ///   - finish:
    public func apiFindScreeningItemBy(param:ScreeningCompare,token:String,sid:String,uuid:String,areaId:String,finish:@escaping((_ re:Bool,_ item:[String:Any])->())){
        let ipAddress = getIpAddress()
        var urlComponents = URLComponents(string: "\(ipAddress)/ehrc/ehr/jksc/list/detail")!
        
        // 添加查询参数
        urlComponents.queryItems = [
            URLQueryItem(name: "areaorg[_type]", value: "area"),
            URLQueryItem(name: "areaorg[areaId]", value: areaId),
            URLQueryItem(name: "areaorg[wgId]", value: ""),
            URLQueryItem(name: "keyword", value: param.personCodeOrIdCard),
            URLQueryItem(name: "qhId", value: areaId),
            URLQueryItem(name: "showQuickJumper", value: "true"),
            URLQueryItem(name: "total", value: "10"),
            URLQueryItem(name: "showSizeChanger", value: "true"),
            URLQueryItem(name: "current", value: "1"),
            URLQueryItem(name: "defaultPageSize", value: "10"),
            URLQueryItem(name: "pageSize", value: "10"),
            URLQueryItem(name: "size", value: "big")
        ]
        
        guard let url = urlComponents.url else {
            print("Invalid URL")
            return
        }
        
        // 创建请求
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        // 设置请求头
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.setValue("mfgAYP3oU7FXKDAO", forHTTPHeaderField: "Dsp-Nydho-Lopr")
        request.setValue("t+CV5Lr4s7zqzod7rxRRVNUs3HDICwbcP82PfH3FjFU9lOJQ8sZKVk6rAPPXWky/em80vmpoZLYG0kuxJAMWdLNVr3kdS/Lgpir/va2WQDCwO0k12yg0vS7BGYdDg7LDZjUMYh0n0mMbOqJo8lthz1NXUsqnlYmXJNGhUH095UpM0EDr5mngtiWZE2BToifVlVmj30mndf4FTEyhAI22SiRBsHQNlid34Q58iOItAUA=", forHTTPHeaderField: "Ehx-Ogyxg-Soex")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("\(ipAddress)/mb.html", forHTTPHeaderField: "Referer")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        
        // 设置 Cookie
        let cookieString = "token=\(token); sid=\(sid); uuid=\(uuid)"
        request.setValue(cookieString, forHTTPHeaderField: "Cookie")
        
        request.writeToLogFile()
        
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "根据参数，查询指定健康筛查接口返回->\(responseString)")
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataDic = dic.dictionary("data")
                        let dataArray = dataDic.array("data")
                        
                        for item in dataArray{
                            if let item1 = ScreeningCompare.deserialize(from: item){
                                if item1.isEquel(by: param){
                                    finish(true,item)
                                    return
                                }
                            }
                        }
                        finish(true,[:])
                        
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false,[:])
                    }
                }else{
                    MyMessage.showText(message: "操作失败，请重试")
                    finish(false,[:])
                }
            }
            
        }
        
        // 启动任务
        task.resume()
    }
    
    
    /// 删除指定的健康筛查
    /// - Parameters:
    ///   - dataId: 数据ID
    ///   - token:
    ///   - sid:
    ///   - uuid:
//    public func apiDeleteScreening(dataId:String,token:String,sid:String,uuid:String,finish:@escaping((_ re:Bool)->())){
//        let ipAddress = getIpAddress()
//        let urlComponents = URLComponents(string: "\(ipAddress)/ehrc/ehr/servicedone/del?type=10.01&fwId=\(dataId)")!
//        
//        guard let url = urlComponents.url else {
//            print("Invalid URL")
//            return
//        }
//        var request = URLRequest(url:url)
//        request.httpMethod = "DELETE"
//        
//        // Set headers
//        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
//        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
//        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
//        request.setValue(token, forHTTPHeaderField: "accessToken")
//        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
//        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
//        request.setValue("\(token)/mb.html", forHTTPHeaderField: "Referer")
//        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
//        request.setValue("O4VLeYUoCYm72d4yVJbTzflUU6bBrTpD1mI7d5ooakFvXO+gM8WRhRkRE+/JlWOdoq8XXFynj9OnzyHS1Wbm1dR+fU5D1txF7PculIeN4thnO7/+XLoeUXNcN3tOoaeHDD7iNvzhhly8KDkLxKtG2lrmUkZe9GSOmS5XeF4wWHjj9v5pE8yzoE8K31qU+5njAlFEpTG+GJdDngTVZFHCOnFaPhBlnyAC2R3KTzrIoHg=", forHTTPHeaderField: "Emp-Crhpr-Pcep")
//        request.setValue("6C4kjLvIh0XcjOwm", forHTTPHeaderField: "Mdl-Hcmmz-Dcml")
//        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
//        request.setValue(ipAddress, forHTTPHeaderField: "Origin")
//        let cookieString = "token=\(token); sid=\(sid); uuid=\(uuid)"
//        request.setValue(cookieString, forHTTPHeaderField: "Cookie")
//        
//        request.writeToLogFile()
//        
//        MyMessage.showWaitHUD()
//        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
//            MyMessage.hiddenWaitHUD()
//            guard let `self` = self else { return }
//            DispatchQueue.main.async {
//                
//                if let data = data, let responseString = String(data: data, encoding: .utf8) {
//                    self.printWrite(log: "删除健康筛查接口返回->\(responseString)")
//                    let dic = responseString.toDic()
//                    let httpCode = dic.intValue("code")
//                    
//                    if httpCode == 200{
//                        finish(true)
//                        
//                    }else{
//                        let httpErrorMsg = dic.strValue("message")
//                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
//                        finish(false)
//                    }
//                }else{
//                    MyMessage.showText(message: "操作失败，请重试")
//                    finish(false)
//                }
//            }
//            
//        }
//        
//        task.resume()
//        
//    }
//    
}

